﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace Freshome.m.vms
{
    internal class Minoraws : TabItemate
    {
        private const string _ep = "wsHttp_IMultint";
        private readonly fox.Userole _ur = null;
        private readonly fox.Helproxy<Rmt.IMultint> _hp;
        private BackgroundWorker _ld = new BackgroundWorker();

        public Minoraws(string nm, fox.Userole ur)
            : base(nm, true)
        {
            this._ur = ur;
            this._hp = new fox.Helproxy<Rmt.IMultint>(ur);
            this._ld.DoWork += new DoWorkEventHandler(Load_DoWork);
            this._ld.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Load_WorkerCompleted);
            this.Content = new vws.Minoraws() { DataContext = this };
        }
        public fox.Helproxy<Rmt.IMultint> Helproxy
        {
            get { return this._hp; }
        }
        public bool Readonly
        {
            get { return !Enabled; }
        }
        private bool _enabled = false;
        public bool Enabled
        {
            get { return _enabled && this._ur.IsJunior; }
            set
            {
                if (_enabled != value)
                {
                    _enabled = value;
                    OnPropertyChanged("Enabled");
                    OnPropertyChanged("Readonly");
                }
            }
        }
        private ObservableCollection<mds.SolidMaterial> _solid = new ObservableCollection<mds.SolidMaterial>();
        public ObservableCollection<mds.SolidMaterial> P_solid
        {
            get { return this._solid; }
        }
        private ObservableCollection<mds.LiquidMaterial> _liquid = new ObservableCollection<mds.LiquidMaterial>();
        public ObservableCollection<mds.LiquidMaterial> P_liquid
        {
            get { return this._liquid; }
        }
        public override void Loadata()
        {
            if (!_ld.IsBusy)
            {
                _ld.RunWorkerAsync();
                this.Enabled = false;
            }
        }
        // Loading finished
        void Load_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null) MessageBox.Show(e.Error.Message, "数据服务");
            else
            {
                var rts = e.Result as Rmt.Minoraw[];
                if (rts != null)
                {
                    fox.Kitools.Refresh(rts.Where(m => m.Category == Rmt.MinorawCateg.Solid), _solid);
                    fox.Kitools.Refresh(rts.Where(m => m.Category == Rmt.MinorawCateg.Liquid), _liquid);
                }
            }
            this.Enabled = true;
        }
        void Load_DoWork(object sender, DoWorkEventArgs e)
        {
            _hp.Asyncall(cln =>
            {
                e.Result = cln.GetMinoraws(false);
            }, new Rmt.MultintClient(_ep));
        }
        private void SaveMinoraws()
        {
            var mis = (from m in _solid where (m.IsValid && m.Created) || m.Updated select m.Raw)
                .Union(from m in _liquid where (m.IsValid && m.Created) || m.Updated select m.Raw);
            if (mis.Count() > 0)
            {
                short mid = short.MinValue; // 为新加记录预设Mid
                foreach (var mi in mis)
                {
                    if(mi.Mid == default(short)) mi.Mid = mid++;
                    mi.Stamp = mi.Name;
                }
                Dictionary<short, string> rts = null;
                _hp.Syncall(cln =>
                {
                    rts = cln.SaveMinoraws(mis.ToArray());
                }, new Rmt.MultintClient(_ep));
                if (rts != null)
                {
                    fox.Kitools.Replace<mds.SolidMaterial, Rmt.Minoraw>(rts, _solid.Where(m => (m.IsValid && m.Created) || m.Updated), "固态佐料");
                    fox.Kitools.Replace<mds.LiquidMaterial, Rmt.Minoraw>(rts, _liquid.Where(m => (m.IsValid && m.Created) || m.Updated), "液态佐料");
                }
            }
        }
        private bool Savable()
        {
            return _solid.Any(m => (m.Created && m.IsValid) || m.Updated)
                || _liquid.Any(m => (m.Created && m.IsValid) || m.Updated);
        }
        private Magicommand _save;
        private void Saventry()
        {
            SaveMinoraws();
        }
        public Magicommand Save
        {
            get
            {
                if (_save == null) _save = new Magicommand(Properties.Resources.Save + "(_S)", param => this.Saventry(), param => this.Savable());
                return _save;
            }
        }
    }
}
